//
//  ZPComposeViewController.swift
//  Weibo
//
//  Created by 张鹏 on 16/7/3.
//  Copyright © 2016年 张鹏. All rights reserved.
//

import UIKit

class ZPComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        // 添加控件
        view.addSubview(composeTextView)
        view.addSubview(composeToolbar)
        composeTextView.addSubview(pictureView)
        // 添加约束
        // 在ios7 以后 系统检测出有导航栏 textView 的文字下移
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        composeToolbar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(composeTextView).offset(10)
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
        }
        // 弹出相册
        pictureView.composePictureViewClosure = {[weak self] ()->() in
            self?.selectImages()
        }
        
        
        
        // 监听composeToolbar 中的按钮店家
        composeToolbar.closure = {[weak self] (type: ZPComposeToolbarType) ->() in
            switch type{
            case .Picture:
                self?.selectImages()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("表情")
            case .Add:
                print("+")
                
            }
            
        }
        
        // 通过系统通知监听键盘
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ZPComposeViewController.keyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    // 监听键盘frame改变
    func keyboardWillChangeFrame(noti: NSNotification){
        // NSRect mac开发中用得 我们移动端开发CGRect 需要我们先把NSRect 转成NSValue
        // 如果rect
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        // 更新toolbar 约束
        composeToolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            // 更新布局
            self.view.layoutIfNeeded()
        }
    }
    
    // 移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    // MARK: -  设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ZPComposeViewController.cancel))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ZPComposeViewController.send))
        // 右侧按钮不能点击
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
    }
    // MARK: - 监听事件
    @objc private func cancel(){
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(false, completion: nil)
    }
    
    @objc private func send(){
        print("发送微博")
        update()
    }
    
    
    // MARK: - 懒加载控件
    private lazy var titleView: UILabel = {
        
        // 显示的文字
        let name = ZPUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        // 最终显示的文字
        let str = "发微博\n\(name)"
        // 获取range
        let range = (str as NSString).rangeOfString(name)
        // 富文本
        let attr = NSMutableAttributedString(string: str)
        
        // 设置富文本
        attr.addAttributes([NSForegroundColorAttributeName: ThemeColor,NSFontAttributeName: UIFont.systemFontOfSize(13)], range: range)
        
        let lab = UILabel()
        lab.attributedText = attr
        lab.textAlignment = .Center
        lab.numberOfLines = 0
        // 设置大小
        lab.sizeToFit()
        return lab
    }()
    // textView
    private lazy var composeTextView: ZPComposeTextView = {
        let view = ZPComposeTextView()
        //        let txt = UITextField()
        //        view.placeholder
        view.placeholder = "我感冒了不想上课我感冒了不想上课我感冒了不想上课我感冒了不想上课我感冒了不想上课我感冒了不想上课我感冒了不想上课"
        view.delegate = self
        // 允许textView 上下拖动
        view.alwaysBounceVertical = true
        // 设置font
        view.font = UIFont.systemFontOfSize(16)
        //view.font
        return view
    }()
    // 底部toolbar
    private lazy var composeToolbar: ZPComposeToolbar = ZPComposeToolbar()
    // 配图
    private lazy var pictureView: ZPComposePictureView = ZPComposePictureView()
    
}
// 处理toolbar按钮点击事件
extension ZPComposeViewController{
    func selectImages() {
        let picker = UIImagePickerController()
        // 设置代理
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
    }
}

extension ZPComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(image)
        composeTextView.backgroundColor = UIColor(patternImage: image)
        
        // 填充图片
        pictureView.addImages(image)
        // 如果实现代理方法 系统将不再帮程序员关闭控制器
        picker.dismissViewControllerAnimated(false, completion: nil)
    }
}

// 发送微博请求
extension ZPComposeViewController{
    // 发送文字微博
    func update(){
        ZPNetworktools.sharedTools.composeUpdate(composeTextView.text, success: { (response) -> () in
            print("发送成功")
        }) { (error) -> () in
            print("发送失败")
        }
        
    }
}

extension ZPComposeViewController: UITextViewDelegate{
    // 监听textView 的文字改变
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
    }
}

